<template>
  <div style="padding:0px 8px">
    <el-card class="configContainer" style="height: 100%;">
      <div style="display: flex;flex-direction: row;align-items: center">
        <h4 class="card-title"> 任务管理 </h4>
        <div class="space"/>
        <el-button type="primary" @click="open = true; title='新增任务'">新增任务</el-button>
      </div>
      <el-divider/>
      <div style="margin: 10px 20px">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item>
            <el-input clearable class="input-150 ml-5" placeholder="请输入任务名" suffix-icon="el-icon-search"
                      v-model="jobName"></el-input>
          </el-form-item>
          <!--            （0允许 1禁止）-->
          <el-form-item>
            <el-select clearable v-model="status" placeholder="请选择状态" style="width:100%">
              <el-option label="允许" :key="0" :value="0"/>
              <el-option label="禁止" :key="1" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select clearable v-model="jobGroup" placeholder="任务组名" style="width:100%">
              <el-option label="默认" :key="0" :value="0"/>
              <el-option label="系统" :key="1" :value="1"/>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </div>

      <el-table height="400px"  :data="tableData" :header-cell-style="{background:'#f8f8f8',height:'40px',color:'#2b2b2b'}"
                style="width: 100%;margin-top: 16px;"
                :cell-style="{'text-align':'center'}"
                @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务编号" width="100" align="center" prop="jobId" />
        <el-table-column label="任务名称" align="center" prop="jobName" :show-overflow-tooltip="true" />
        <el-table-column label="任务组名" align="center" prop="jobGroup">
          <template #default="scope">
            <el-tag v-if="scope.row.jobGroup == 0" type="success">默认</el-tag>
            <el-tag v-else-if="scope.row.jobGroup == 1" type="primary">系统</el-tag>
            <el-tag v-else="" type="warning">未知</el-tag>
          </template>

        </el-table-column>
        <el-table-column label="调用目标字符串" align="center" prop="invokeTarget" :show-overflow-tooltip="true" />
        <el-table-column label="cron执行表达式" align="center" prop="cronExpression" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
                size="mini"
                type="text"
                @click="open = true; title='修改任务';form = scope.row"
            >
              <el-icon>
                <Edit/>
              </el-icon>
              修改</el-button>

            <el-popconfirm title="确认删除吗?" @confirm="del(scope.row.jobId)">
              <template #reference>
                <el-button link type="danger" size="small">
                  <el-icon>
                    <Delete/>
                  </el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <template #dropdown>
                <el-dropdown-item command="handleRun"
                                  v-hasPermi="['monitor:job:changeStatus']">
                  <el-icon><CaretRight /></el-icon>
                  执行一次</el-dropdown-item>
<!--                <el-dropdown-item command="handleView" icon="el-icon-view"-->
<!--                                  v-hasPermi="['monitor:job:query']">任务详细</el-dropdown-item>-->
<!--                <el-dropdown-item command="handleJobLog" icon="el-icon-s-operation"-->
<!--                                  v-hasPermi="['monitor:job:query']">调度日志</el-dropdown-item>-->
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :page-sizes="[10, 20, 50, 100]"
          :page-count="pagecount"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="currentChange"
          style="margin-top: 16px;width: 100%;display: flex;align-items: center;justify-content: center;"
          background layout="total, sizes, prev, pager, next, jumper"/>
    </el-card>
    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入任务名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-select v-model="form.jobGroup" placeholder="请选择任务分组">
                <el-option label="默认"  value="0"/>
                <el-option label="系统"  value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="invokeTarget">
              <template #label>
              <span slot="label">
                调用方法
                <el-tooltip effect="dark" placement="top-start">
                  <el-icon><QuestionFilled/></el-icon>
                       <template #content>
                       <div slot="content">
                        Bean调用示例：task.test1('hello')
                        <br />Class类调用示例：com.icbc.quartz.task.task.test1('hello')
                        <br />参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                        </div>
                       </template>
                </el-tooltip>
              </span>
              </template>
              <el-input v-model="form.invokeTarget" placeholder="请输入调用目标字符串"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式">
                <template #append>
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="执行策略" prop="misfirePolicy">
              <el-radio-group v-model="form.misfirePolicy" size="small">
                <el-radio-button label="1">立即执行</el-radio-button>
                <el-radio-button label="2">执行一次</el-radio-button>
                <el-radio-button label="3">放弃执行</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="form.concurrent" size="small">
                <el-radio-button label="0">允许</el-radio-button>
                <el-radio-button label="1">禁止</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">暂停</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false;form = {}">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="任务详细" v-model="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号：">{{ form.jobId }}</el-form-item>
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">
              <el-select v-model="form.jobGroup">
                <el-option label="默认" :key="null" :value="null"/>
                <el-option label="系统" :key="200" :value="200"/>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{ form.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：">{{ parseTime(form.nextValidTime) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标方法：">{{ form.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">
              <div v-if="form.status == 0">正常</div>
              <div v-else-if="form.status == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：">
              <div v-if="form.concurrent == 0">允许</div>
              <div v-else-if="form.concurrent == 1">禁止</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：">
              <div v-if="form.misfirePolicy == 0">默认策略</div>
              <div v-else-if="form.misfirePolicy == 1">立即执行</div>
              <div v-else-if="form.misfirePolicy == 2">执行一次</div>
              <div v-else-if="form.misfirePolicy == 3">放弃执行</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="Cron表达式生成器" v-model="openCron" append-to-body destroy-on-close>
      <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>
  </div>
  <CompanyText/>
</template>

<script>
import CompanyText from "../../../components/CompanyText.vue";
//当前使用的页面引入


import Crontab from '../../../components/Crontab/index.vue'




export default {
  name: "taskJob",
  components: {
    CompanyText,Crontab
  },
  data() {
    return {
      option:[{value:0,text:"默认"},{value:1,text:"系统"}],
      title: "",
      open: false,
      openView: false,
      openCron: false,
      expression: "",
      JsonData: {},
      show: false,
      tableData: [],
      status: null,
      jobName: null,
      jobGroup: null,
      multipleSelection: [],
      pageNum: 1,
      pagesize: 10,
      total: 0,
      startTime: null,
      endTime: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jobName: [
          {required: true, message: "任务名称不能为空", trigger: "blur"}
        ],
        invokeTarget: [
          {required: true, message: "调用目标字符串不能为空", trigger: "blur"}
        ],
        cronExpression: [
          {required: true, message: "cron执行表达式不能为空", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.load()
  },
  methods: {
    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.cronExpression;
      this.openCron = true;
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cronExpression = value;
    },
    showJson(title, JsonData) {
      this.show = true;
      this.JsonData = JSON.parse(JsonData)
      console.info(this.JsonData)
      this.title = title
    },
    load() {
      this.$http.post("/taskJob/getList",
       {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          jobName: this.jobName,
          jobGroup: this.jobGroup,
          status: this.status
        }
      ).then(res => {
        this.tableData = res.data.records;
        this.pagecount = res.data.pages;
        this.total = res.data.total;
        this.current = res.data.current;
      })
    },
    del(id) {
      this.$http.post("/taskJob/del", {
        'jobId': id
      }).then(res => {
        console.info(res.statusCode);
        if (res.code === 0) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleRun":
          this.handleRun(row);
          break;
        case "handleView":
          this.handleView(row);
          break;
        case "handleJobLog":
          this.handleJobLog(row);
          break;
        default:
          break;
      }
    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.jobId != undefined) {
            that.edit();
          } else {
            that.add();
          }
        }
      });
    },
    handleRun(row){
      let that = this;
      this.$http.post('/taskJob/run',
          row
      ).then(function (response) {
        console.log('success' + response.data);
        if (response.code === 0) {
          console.log('success');
          that.$message({
            message: response.userMsg,
            type: 'success'
          });
          that.open = false;
          that.load()
        }
      }).catch(function (error) {
        console.log('error');
      });
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    add() {
      let that = this;
      this.$http.post('/taskJob/add',
          that.form
      ).then(function (response) {
        console.log('success' + response.data);
        if (response.code === 0) {
          console.log('success');
          that.$message.success(response.userMsg)
          that.open = false;
          that.load()
        }
      }).catch(function (error) {
        console.log('error');
      });
    },
    edit() {
      let that = this;
      this.$http.post('/taskJob/edit',
          that.form
      ).then(function (response) {
        console.log('success' + response.data);
        if (response.code === 0) {
          console.log('success');
          that.$message.success(response.userMsg)
          that.open = false;
          that.load()
        }
      }).catch(function (error) {
        console.log('error');
      });
    },
    handleStatusChange(row) {
      let that = this;
      this.$http.post('/taskJob/change',
          row
      ).then(function (response) {
        console.log('success' + response.data);
        if (response.code === 0) {
          console.log('success');
          that.$message.success(response.userMsg)
          that.open = false;
          that.load()
        }
      }).catch(function (error) {
        console.log('error');
      });
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      let data = new FormData();
      data.append('ids', ids);
      this.$http.post("/taskJob/delBatchById", data).then(res => {
        console.info(res)
        if (res.code === 0) {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("批量删除失败")
        }
      })
    },
    reset() {
      this.jobName = null
      this.status = null
      this.startTime = null
      this.endTime = null
      this.jobGroup = null
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    currentChange(current) {
      this.pageNum = current;
      console.info(this.current)
      this.load();
    },
    // 日期格式化
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
          return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    }

  }
}
</script>

<style scoped>

.my-awesome-json-theme {
  background: #fff;
  white-space: nowrap;
  color: #525252;
  font-size: 14px;
  font-family: Consolas, Menlo, Courier, monospace;
}

.jv-ellipsis {
  color: #999;
  background-color: #eee;
  display: inline-block;
  line-height: 0.9;
  font-size: 0.9em;
  padding: 0px 4px 2px 4px;
  border-radius: 3px;
  vertical-align: 2px;
  cursor: pointer;
  user-select: none;
}

.jv-button {
  color: #49b3ff
}


.jv-array {
  color: #111111
}


.jv-boolean {
  color: #fc1e70
}

.jv-function {
  color: #067bca
}

.jv-number {
  color: #fc1e70
}

.jv-number-float {
  color: #fc1e70
}

.jv-number-integer {
  color: #fc1e70
}

.jv-object {
  color: #111111
}

.jv-undefined {
  color: #e08331
}

.jv-string {
  color: #42b983;
  word-break: break-word;
  white-space: normal;
}


:before {
  padding: 0px 2px;
  border-radius: 2px;
}


:before {
  background: #eee;
}


.req-string {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.req-type-box {
  color: #FFF;
}

.req-type-box b {
  padding: 3px 7px;
  border-radius: 3px;
  font-size: 12px;
}

.cursor {
  cursor: pointer;
}

.jv-key {
  color: tomato;
  margin-right: 4px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: center;
}

.bidMethod {
  position: relative;
}

.smartTip {
  position: absolute;
  left: -113px;
  top: 6px;
}
.configContainer {
  margin: 10px 8px;
  padding: 0px;
  /* border: red 1px solid; */
}
</style>
